package celiasoft.itasalib.query;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.htmlcleaner.TagNode;

import android.util.Log;
import celiasoft.itasalib.filegatherer.HTMLGatherer;
import celiasoft.itasalib.query.result.QueryResult;
import celiasoft.itasalib.query.result.QueryResultError;
import celiasoft.itasalib.query.resultparser.IQueryResultParser;
import celiasoft.itasalib.query.resultparser.QueryCalendarResultParser;
import celiasoft.itasalib.staticdata.ItasaStaticUrls;
import celiasoft.itasalib.structures.DataElement;

public class CalendarQuery extends Query {

	private final static String TAG = "itasalib.query.CalendarQuery";
	private Date _day;

	public CalendarQuery(HTMLGatherer gatherer) {
		super(gatherer, null);
	}

	@Override
	protected String getQueryUrl() {
		
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");
		return String.format(ItasaStaticUrls.SHOW_CALENDAR_URL, dateformat.format( this._day ));
	}

	public Date getCalDay(){
		return this._day;
	}
	
	public void setCalDay(Date day){
		this._day = day;
	}
	
	
	@Override
	protected IQueryResultParser getResultParser() {
		
		return new QueryCalendarResultParser();
	}

	
	@Override
	public QueryResult execute() {
		String queryUrl = this.getQueryUrl().replaceAll("&$", "");
		Log.d(TAG, "Actual query:" + queryUrl);
		
		if(queryUrl != null){
			
			TagNode root = this.getGatherer().getRootNode(queryUrl);
			
			return  buildResult(root);
			
		}
		
		return null;
	}

	private QueryResult buildResult(TagNode root) {
		
		if(root == null){
			return new QueryResult(new QueryResultError(400, "Generic Error"));
		}
		
		QueryResult qr = this.getErrParser().parse(root);
		if(qr != null){
			return qr;
		}
		
		ResultsMetaInfo meta = new ResultsMetaInfo();
		List<DataElement> res = getResultParser().parse(root, meta);
		if(res != null){
			Log.d(TAG, "ok");
			return new QueryResult(res, meta);
		}
		
		Log.d(TAG, "null");
		return null;
	}

	
}
